package com.threesome.memos.dialog;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.threesome.memos.R;

public class SinglePicker extends Activity {
	public static final String TITLE = "title";
	public static final String ITEMS_ARRAY = "items_array";
	public static final String SELECTED_POSITION = "selected_position";
	private Context mContext;
	private ArrayList<String> mItemsArray;
	private int mSelectetPos;
	private SingleAdapter mAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.dialog_single_picker);
		mContext = this;
		
		((TextView)findViewById(R.id.title)).setText(getIntent().getStringExtra(TITLE));
		
		mSelectetPos = getIntent().getIntExtra(SELECTED_POSITION, 0);
		mItemsArray = getIntent().getStringArrayListExtra(ITEMS_ARRAY);
		if(mItemsArray == null) {
			finish();
			return;
		}
		
		ListView list = (ListView)findViewById(R.id.list);
		mAdapter = new SingleAdapter();
		list.setAdapter(mAdapter);
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				mSelectetPos = position;
				Intent intent = new Intent();
				intent.putExtra(SELECTED_POSITION, mSelectetPos);
				setResult(Activity.RESULT_OK, intent);
				finish();
			}			
		});
	}

	private class SingleAdapter extends BaseAdapter {
		LayoutInflater mInflater = LayoutInflater.from(mContext);
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = mInflater.inflate(R.layout.dialog_single_or_multi_button, null);
			TextView text = (TextView)convertView.findViewById(R.id.text);
			RadioButton radioButton = (RadioButton)convertView.findViewById(R.id.radioButton);
			text.setText(mItemsArray.get(position));
			if(mSelectetPos == position) {
				radioButton.setChecked(true);
			}
			else {
				radioButton.setChecked(false);
			}
			return convertView;
		}
		
		@Override
		public int getCount() {
			return mItemsArray.size();
		}

		@Override
		public Object getItem(int position) {
			return mItemsArray.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}
		
	}
}
